package org.jeecg.modules.demo.hdFileRetention.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.hdFileRetention.entity.HdFileRetention;
import org.jeecg.modules.demo.hdFileRetention.mapper.HdFileRetentionMapper;
import org.jeecg.modules.demo.hdFileRetention.service.IHdFileRetentionService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 文件留档
 * @Author: jeecg-boot
 * @Date:   2025-07-12
 * @Version: V1.0
 */
@Service
public class HdFileRetentionServiceImpl extends ServiceImpl<HdFileRetentionMapper, HdFileRetention> implements IHdFileRetentionService {

    @Override
    public String uploadSceneFile(HdFileRetention hdFileRetention) {

        this.addHdFileRetention(hdFileRetention);
        return "添加成功";
    }

    @Override
    public void addHdFileRetention(HdFileRetention hdFileRetention) {
        //新增时设置hasChild为0
        hdFileRetention.setHasChild(IHdFileRetentionService.NOCHILD);
        if(oConvertUtils.isEmpty(hdFileRetention.getPid())){
            hdFileRetention.setPid(IHdFileRetentionService.ROOT_PID_VALUE);
        }else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            HdFileRetention parent = baseMapper.selectById(hdFileRetention.getPid());
            if(parent!=null && !"1".equals(parent.getHasChild())){
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }
        }
        baseMapper.insert(hdFileRetention);
    }


    @Override
    public void updateHdFileRetention(HdFileRetention hdFileRetention) {
        HdFileRetention entity = this.getById(hdFileRetention.getId());
        if(entity==null) {
            throw new JeecgBootException("未找到对应实体");
        }
        String old_pid = entity.getPid();
        String new_pid = hdFileRetention.getPid();
        if(!old_pid.equals(new_pid)) {
            updateOldParentNode(old_pid);
            if(oConvertUtils.isEmpty(new_pid)){
                hdFileRetention.setPid(IHdFileRetentionService.ROOT_PID_VALUE);
            }
            if(!IHdFileRetentionService.ROOT_PID_VALUE.equals(hdFileRetention.getPid())) {
                baseMapper.updateTreeNodeStatus(hdFileRetention.getPid(), IHdFileRetentionService.HASCHILD);
            }
        }
        baseMapper.updateById(hdFileRetention);
    }

    @Override
    public void removeHdFileRetention(String id) {
        //查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    HdFileRetention hdFileRetention = this.getById(idVal);
                    String pidVal = hdFileRetention.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<HdFileRetention> dataList = baseMapper.selectList(new QueryWrapper<HdFileRetention>().eq("pid", pidVal).notIn("id", Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            HdFileRetention hdFileRetention = this.getById(id);
            if(hdFileRetention==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(hdFileRetention.getPid());
            baseMapper.deleteById(id);
        }
    }

    @Override
    public void removeAll(List<String> list) {
        LambdaQueryWrapper<HdFileRetention> queryWrapper = new LambdaQueryWrapper<>();
        baseMapper.delete(queryWrapper.in(HdFileRetention::getPid, list));
    }

    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<HdFileRetention> dataList = baseMapper.selectList(new QueryWrapper<HdFileRetention>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(HdFileRetention tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }
    private void updateOldParentNode(String pid) {
        if(!IHdFileRetentionService.ROOT_PID_VALUE.equals(pid)) {
            Long count = baseMapper.selectCount(new QueryWrapper<HdFileRetention>().eq("pid", pid));
            if(count==null || count<=1) {
                baseMapper.updateTreeNodeStatus(pid, IHdFileRetentionService.NOCHILD);
            }
        }
    }


    //文件夹删除
    public static void deleteFolder(File folder) {
        // 验证是否为文件夹
        if (folder.isDirectory()) {
            // 获取文件夹中的所有文件和子文件夹
            File[] files = folder.listFiles();

            if (files != null) {
                // 递归删除文件夹中的所有文件和子文件夹
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        // 删除空文件夹
        boolean isDeleted = folder.delete();

        if (isDeleted) {
            System.out.println("Folder deleted: " + folder.getAbsolutePath());
        } else {
            System.out.println("Failed to delete folder: " + folder.getAbsolutePath());
        }
    }


}
